package com.lwy.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.lwy.dto.SDKMember;
import com.lwy.dto.TLSSigAPIv2;
import com.lwy.enums.ImSDKType;
import com.lwy.service.ImSDKService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.security.SecureRandom;
import java.util.*;

@Service
@Slf4j
public class ImSDKServiceImpl implements ImSDKService {

    @Autowired
    private RestTemplate restTemplate;

    //request前缀
    private static final String URL_IP = "https://console.tim.qq.com/v4/group_open_http_svc/";
    private static final long SDK_APPID = 1400707306;
    private static final String SECRET_KEY = "438a0827e9987eb5ad771e1341ec21d27c46fd5704aba74c28a70a64d59723b8";
    private long expire = 60*60*24*7;
    private static final String USER_ID = "dinggu";


    @Override
    public String createGroup(ImSDKType imSDKType, String groupId, String groupName, String leaderUserId) {
        Map<String,String> body = new HashMap<>();
        body.put("Type",imSDKType.name());
        body.put("GroupId",groupId);
        if (StringUtils.isNotBlank(groupName)){
            body.put("Name",groupName);
        }
        if (StringUtils.isNotBlank(leaderUserId)){
            body.put("Owner_Account",leaderUserId);
        }
        JSONObject response = request("create_group",body,JSONObject.class);
        if (!Objects.equals("0",response.getString("ErrorCode"))){
            throw new IllegalStateException("ErrorCode!=0 调用腾讯Im失败");
        }else{
            return response.getString("ActionStatus");
        }
    }

    @Override
    public String addGroupUser(String groupId, List<SDKMember> SDKMembers) {
        Map<String, Object> body = new HashMap<>();
        body.put("GroupId",groupId);
        //这里可能序列化会有坑 导致字段小写 所以处理一下
        body.put("MemberList",getMemberList(SDKMembers));
        JSONObject response = request("add_group_member",body,JSONObject.class);
        if (!Objects.equals("0",response.getString("ErrorCode"))){
            throw new IllegalStateException("ErrorCode!=0 调用腾讯Im失败");
        }else{
            return response.getString("ActionStatus");
        }
    }

    @Override
    public String delGroupUser(String groupId, List<String> userIds) {
        Map<String,Object> body = new HashMap<>();
        body.put("GroupId",groupId);
        body.put("MemberToDel_Account",userIds);
        JSONObject response = request("delete_group_member",body,JSONObject.class);
        if (!Objects.equals("0",response.getString("ErrorCode"))){
            throw new IllegalStateException("ErrorCode!=0 调用腾讯Im失败");
        }else{
            return response.getString("ActionStatus");
        }
    }

    private <Q,T> T request(String command, Q body, Class<T> responseClass) {
        String url = getUrl(command);
        HttpHeaders  httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Q> httpEntity = new HttpEntity<>(body,httpHeaders);
        log.info("request - body|url:{}|{}",JSON.toJSONString(body),url);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, httpEntity, responseClass);
        log.info("request - responseEntity:{}",JSON.toJSONString(responseEntity));
        return responseEntity.getBody();
    }

    private String getUrl(String command) {
        Map<String,Object> params = addCommonParams();
        StringBuilder sb = new StringBuilder().append(URL_IP).append(command).append('?');
        boolean flag = true;
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (!flag){
                sb.append("&");
            }else{
                flag = false;
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString();
    }

    private Map<String, Object> addCommonParams() {
        Map<String,Object> map = new HashMap<>();
        map.put("sdkappid",SDK_APPID);
        map.put("usersig",getUserSig(USER_ID));
        map.put("random",Math.abs(new SecureRandom().nextInt()));
        map.put("identifier",USER_ID);
        map.put("contenttype","json");
        return map;
    }

    private String getUserSig(String userId) {
        TLSSigAPIv2 api = new TLSSigAPIv2(SDK_APPID,SECRET_KEY);
        return api.genUserSig(userId,expire);
    }

    private Object getMemberList(List<SDKMember> sdkMembers) {
        List<Map<String,String>> list = new ArrayList<>();
        sdkMembers.forEach(item ->{
            Map<String,String> member = new HashMap<>();
            member.put("Member_Account",item.getMember_Account());
            if (StringUtils.isNotBlank(item.getRole())){
                member.put("Role",item.getRole());
            }
            list.add(member);
        });
        return list;
    }
}
